import {
	defineStore
} from 'pinia'
import {
	ref
} from 'vue'
import user from '@/api/user.js'

export const useUserStore = defineStore('user', () => {
	const role = ref(1)
	const setRole = (newRole) => {
		role.value = newRole
		uni.setTabBarItem({
			index: 1,
			text: newRole == 1 ? '宠物出行' : '接单大厅',
		})
	}
	const setTitle = (newRole) => {
		role.value = newRole
		uni.setNavigationBarTitle({
			title: newRole == 1 ? '宠物出行' : '接单大厅',
		});
	}

	const locationInterval = ref()
	const changeLocation = async () => {
		updateDriverLocation()
		clearLocationInterval()
		locationInterval.value = setInterval(() => {
			updateDriverLocation()
		}, 60000)
	}
	const updateDriverLocation =  () => {
		uni.getFuzzyLocation({
			type: 'wgs84',
			success: async function(res) {
				console.log('更新司机定位', res);
				await user.updateDriverLocation({
					lat: res.latitude,
					lng: res.longitude
				})
			},
			fail(e) {
				console.log('失败', e);
			}
		});
	}
	const clearLocationInterval = () => {
		clearInterval(locationInterval.value)
	}
	return {
		role,
		setRole,
		setTitle,
		changeLocation,
		clearLocationInterval
	}
}, {
	persist: {
		storage: {
			getItem(key) {
				return uni.getStorageSync(key)
			},
			setItem(key, val) {
				uni.setStorageSync(key, val)
			}
		}
	}
})